import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/entity/pay/coupon_pack_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/server/api/coupon_api.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/circular.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:sports_new/widgets/base/qkd_text.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../../entity/pay/recharge_entity.dart';
import '../../../server/api/pay_api.dart';
import '../../../utils/routes.dart';
import '../../../utils/toast_utils.dart';
import '../../../utils/user.dart';
import '../../../widgets/pay_bottom_sheet.dart';

class CouponSaleItem extends StatefulWidget {
  const CouponSaleItem({super.key,
    required this.entity,
    this.padding,
    this.margin
  });

  final ResourceEntity? entity;
  final EdgeInsets? padding;
  final EdgeInsets? margin;

  @override
  State<CouponSaleItem> createState() => _CouponSaleItemState();
}

class _CouponSaleItemState extends State<CouponSaleItem> {
  CouponPackEntity? entity;

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async{
    entity = await CouponApi.getCouponPackSingle(widget.entity?.content.toInt()??0);
    SpUtils.couponSale = SpUtils.couponSale+1;
    setState(() {});
  }


  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: const Key("coupon_pack_item"),
      onVisibilityChanged: (VisibilityInfo info) {
        if(!info.visibleBounds.isEmpty) getData();
      },
      child:entity?.price == null||entity?.nextPayTime.hasValue == true|| SpUtils.couponSale > 10?Container():Circular(
        color: Colours.white,
        radius: 8,
        padding: widget.padding,
        margin: widget.margin,
        clipBehavior: Clip.antiAlias,
        child: Stack(
          alignment: AlignmentDirectional.topEnd,
          children: [
            Column(
              children: [
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => Get.dialog(
                        QkdDialog.single("券包优惠购说明",content: widget.entity?.extInfo)
                      ),
                      child: Image.asset(
                        Utils.getImgPath('coupon_sale_title.png'),
                        height: 42
                      ),
                    ),
                    const Spacer(),
                    GestureDetector(
                      onTap: () => User.needLogin(() => toPay()),
                      child: Circular(
                        margin: const EdgeInsets.only(right: 20),
                        padding: const EdgeInsets.symmetric(horizontal: 11,vertical: 4),
                        radius: 16.5,
                        gradient: const LinearGradient(colors: [Color(0xFFF5402B),Color(0xFFF0297C)]),
                        child: QkdText(
                          "${entity?.price?.toStringAsFixed(2)}球币购买",
                          fontSize: 12,color: Colours.white
                        )
                      ),
                    )
                  ],
                ),
                if(widget.entity?.imgUrl.hasValue??false)...[
                  Container(height: 3),
                  GestureDetector(
                    onTap: () => Get.toNamed(Routes.saleCenter,arguments: "超值券包"),
                    child: Container(
                      padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                      child: QkdImage(
                        imageUrl: widget.entity!.imgUrl??"",
                        width: Get.width, height: null,
                        fit: BoxFit.cover,
                      ),
                    ),
                  )
                ]
              ],
            ),
            GestureDetector(
              onTap: (){
                SpUtils.couponSale = 11;
                setState(() {});
              },
              child: Circular(
                width: 16,height: 16,
                color: Colours.grey99,
                alignment: Alignment.center,
                borderRadius: const BorderRadius.only(
                  topRight: Radius.circular(8),
                  bottomLeft: Radius.circular(8)
                ),
                child: Image.asset(
                  Utils.getImgPath('close_48.png'),
                  width: 12,height: 12,color: Colours.white
                )
              ),
            )
          ],
        )
      ),
    );
  }

  Future toPay() async{
    double money = entity?.price ?? 0;
    final PayResult? result = await Get.bottomSheet(
        isScrollControlled: true,
        PayBottomSheet(
            payInfo: PayInfo(
                price: money.toStringAsFixed(2),
                payScene: PayScene.couponPack,
                buyId: "${entity?.id}"
            )
        )
    );
    if(result != null && result.toPay == PayStatus.goldPay){
      var s = await PayApi.couponPackOrder(entity?.id);
      if(s == true) {
        getData();
        Utils.onEvent('pay_done');
        if(Get.previousRoute.contains(Routes.myCoupons)){
          Get.back();
        }else{
          Get.toNamed(Routes.myCoupons);
        }
      }else{
        Utils.onEvent('aizh_zfyd_qxzf');
      }
    }else if(result?.toPay == PayStatus.directPay){
      getData();
      Utils.onEvent('aizh_zfyd_qrzf');
      if(Get.previousRoute.contains(Routes.myCoupons)){
        Get.back();
      }else{
        Get.toNamed(Routes.myCoupons);
      }
    }else{
      Utils.onEvent('aizh_zfyd_qxzf');
      ToastUtils.show("购买失败");
    }
    User.fetchUserInfo(fetchFocus: false);
  }
}
